<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <img src="@/assets/airline-logo.png" alt="航空公司Logo" class="logo">
        <h1>天津滨海机场航班分析及管理平台</h1>
        <p class="subtitle">请使用您的账号登录系统</p>
      </div>

      <el-form
        ref="loginFormRef"
        :model="form"
        :rules="rules"
        label-position="top"
        class="login-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
            clearable
            size="large"
          >
            <template #prefix>
              <el-icon class="input-icon"><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            show-password
            size="large"
          >
            <template #prefix>
              <el-icon class="input-icon"><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="captcha">
          <div class="captcha-row">
            <el-input
              v-model="form.captcha"
              placeholder="请输入验证码"
              size="large"
              style="flex: 1"
            >
              <template #prefix>
                <el-icon class="input-icon"><Key /></el-icon>
              </template>
            </el-input>
            <div class="captcha-display" @click="refreshCaptcha">
              {{ captchaText }}
            </div>
          </div>
        </el-form-item>

        <el-form-item prop="agreed">
          <el-checkbox v-model="form.agreed" size="large">
            我已阅读并同意
            <el-link type="primary" @click="showAgreement = true">《用户协议》</el-link>
          </el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleLogin"
            size="large"
            :loading="loading"
            class="login-btn"
          >
            登 录
          </el-button>
        </el-form-item>
      </el-form>

      <div class="login-footer">
        <div class="footer-links">
          <el-link type="info" @click="$router.push('/forgot-password')">忘记密码？</el-link>
          <el-link type="info" @click="$router.push('/register')">还没有账号？</el-link>
        </div>
      </div>
    </div>

    <el-dialog v-model="showAgreement" title="用户协议" width="50%">
      <div class="agreement-content">
        <h3>天津滨海机场航班分析及管理平台用户协议</h3>
        <p>1. 用户在使用本平台服务前，请务必仔细阅读并理解本协议的全部内容。</p>
        <p>2. 用户应保证提供的账号信息真实、准确、完整，并及时更新。</p>
        <p>3. 用户不得将账号转让或出借给他人使用，否则应承担由此产生的全部责任。</p>
        <p>4. 用户应妥善保管账号及密码安全，对通过账号进行的操作承担法律责任。</p>
        <p>5. 本平台有权根据业务需要调整服务内容，并保留随时修改本协议的权利。</p>
      </div>
      <template #footer>
        <el-button type="primary" @click="showAgreement = false">我已阅读</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { login } from '@/api/flight'
import { User, Lock, Key } from '@element-plus/icons-vue'

const router = useRouter()
const store = useStore()

const form = ref({
  username: '',
  password: '',
  captcha: '',
  agreed: false
})

const loginFormRef = ref(null)
const loading = ref(false)
const showAgreement = ref(false)
const captchaText = ref('')
const correctCaptcha = ref('')

const validateCaptcha = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入验证码'))
  } else if (value.toLowerCase() !== correctCaptcha.value.toLowerCase()) {
    callback(new Error('验证码不正确'))
  } else {
    callback()
  }
}

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { validator: validateCaptcha, trigger: 'blur' }
  ],
  agreed: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请同意用户协议'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

const generateCaptcha = () => {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let result = ''
  for (let i = 0; i < 4; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  correctCaptcha.value = result
  captchaText.value = result.split('').map(c =>
    Math.random() > 0.5 ? c.toLowerCase() : c
  ).join('')
}

const refreshCaptcha = () => {
  generateCaptcha()
}

const handleLogin = async () => {
  try {
    loading.value = true
    await loginFormRef.value.validate()

    const formData = new FormData()
    formData.append('username', form.value.username)
    formData.append('password', form.value.password)

    const response = await login(formData)
    if (!response?.token) {
      throw new Error(response?.message || '登录失败')
    }

    // 存储完整用户信息
    store.commit('setUser', {
      id: response.id,
      username: response.username,
      email: response.email,
      phone: response.phone,
      role: response.roles[0].toLowerCase(),
      createTime: response.createTime
    })
    localStorage.setItem('token', response.token)
    localStorage.setItem('role', response.roles[0])

    const role = response.roles[0].toLowerCase()
    router.push(role === 'admin' ? '/home/dashboard' : '/home/dashboard')
    ElMessage.success(`欢迎 ${form.value.username}`)
  } catch (error) {
    console.error('登录错误:', error)
    ElMessage.error(error.message || '登录失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  generateCaptcha()
})
</script>
<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: url('@/assets/airport-bg.jpg') no-repeat center center;
  background-size: cover;
  position: relative;
  padding: 20px;
}

.login-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 0;
}

.login-box {
  width: 420px; /* 适中宽度 */
  padding: 35px; /* 适度内边距 */
  background: rgba(255, 255, 255, 0.96); /* 提高透明度 */
  border-radius: 12px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15); /* 更柔和的阴影 */
  position: relative;
  z-index: 1;
  animation: fadeIn 0.5s ease; /* 添加淡入动画 */
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.logo {
  height: 55px; /* 适中大小 */
  margin-bottom: 18px;
  transition: transform 0.3s; /* 添加悬停效果 */
}

.logo:hover {
  transform: scale(1.05);
}

.login-header {
  text-align: center;
  margin-bottom: 25px;
}

.login-header h1 {
  font-size: 22px; /* 适中字号 */
  margin-bottom: 8px;
  color: #333;
  font-weight: 600; /* 稍加粗 */
  letter-spacing: 0.5px; /* 字母间距 */
}

.subtitle {
  font-size: 14px;
  color: #666;
  letter-spacing: 0.3px;
}

.login-form {
  margin-top: 18px;
}

.captcha-row {
  display: flex;
  gap: 10px;
  align-items: center;
}

.captcha-display {
  width: 110px;
  height: 38px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%); /* 渐变背景 */
  border-radius: 6px; /* 更圆润 */
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: monospace;
  font-size: 19px;
  font-weight: bold;
  letter-spacing: 2px;
  color: #333;
  cursor: pointer;
  user-select: none;
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
}

.captcha-display:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.login-btn {
  width: 100%;
  margin-top: 12px;
  font-size: 16px;
  letter-spacing: 2px;
  height: 44px; /* 固定高度 */
  transition: all 0.3s;
}

.login-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.footer-links {
  display: flex;
  justify-content: space-between;
  margin-top: 18px;
  padding-top: 18px;
  border-top: 1px solid #eee;
}

.footer-links .el-link {
  font-size: 13px;
  transition: color 0.3s;
}

.footer-links .el-link:hover {
  color: #409EFF !important;
}

.input-icon {
  color: #999;
  margin-right: 8px;
  font-size: 18px;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .login-box {
    width: 90%;
    padding: 25px;
  }

  .login-header h1 {
    font-size: 20px;
  }
}
</style>
